package org.demos.server.core;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import org.demos.server.pojo.ServiceInstance;

/**
 * 注册核心-注册表
 *
 * @author bing.zhang06@hand-china.com 2021/10/26 15:47
 **/
public class Registry {
    private static Registry instance = new Registry();

    /**
     * 该对象为单例 bean
     */
    private Registry() {

    }

    /**
     * 核心的内存数据结构：注册表
     * Map：key是服务名称，value是这个服务的所有的服务实例
     * Map<String, ServiceInstance>：key是服务实例id，value是服务实例的信息
     */
    private final Map<String, Map<String, ServiceInstance>> registryMap
            = new HashMap<String, Map<String, ServiceInstance>>();

    /**
     * 服务注册
     *
     * @param serviceInstance 服务实例
     */
    public void register(ServiceInstance serviceInstance) {
        String serviceName = serviceInstance.getServiceName();

        Map<String, ServiceInstance> instanceMap
                = registryMap.computeIfAbsent(serviceName, anonymous -> new HashMap<String, ServiceInstance>());

        String serviceInstanceId = serviceInstance.getServiceInstanceId();
        // 将注册信息保存至 Map
        instanceMap.put(serviceInstanceId, serviceInstance);

        System.out.println("服务实例【" + serviceInstance + "】，" + DateUtil.now() + " 完成注册......");
        System.out.println("注册表：" + registryMap);
    }


    /**
     * 获取服务实例
     *
     * @param serviceName       服务名称
     * @param serviceInstanceId 服务实例id
     * @return 服务实例
     */
    public ServiceInstance getServiceInstance(String serviceName,
                                              String serviceInstanceId) {
        Map<String, ServiceInstance> serviceInstanceMap = registryMap.get(serviceName);
        return serviceInstanceMap.get(serviceInstanceId);
    }

    /**
     * 获取整个注册表
     *
     * @return 注册表 Map
     */
    public Map<String, Map<String, ServiceInstance>> getRegistry() {
        return registryMap;
    }

    /**
     * 从注册表删除一个服务实例
     *
     * @param serviceName       服务名称
     * @param serviceInstanceId 服务实例 id
     */
    public void remove(String serviceName, String serviceInstanceId) {
        System.out.println("服务实例【" + serviceInstanceId + "】，" + DateUtil.now() + "从注册表中进行摘除");
        Map<String, ServiceInstance> serviceInstanceMap = registryMap.get(serviceName);
        serviceInstanceMap.remove(serviceInstanceId);
    }

    /**
     * 获取注册表对象
     *
     * @return 注册表对象
     */
    public static Registry getInstance() {
        return instance;
    }
}
